package cn.stylefeng.guns.modular.hx.storage.controller;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPut;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutDetailed;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStoragePut;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStoragePutDetailed;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutResult;
import cn.stylefeng.guns.modular.hx.storage.service.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 入库单表控制器
 *
 * @author zhucx
 * @Date 2023-08-14 10:54:09
 */
@Controller
@RequestMapping("/hxStoragePut")
public class HxStoragePutController extends BaseController {

    private String PREFIX = "/hx/storage/hxStoragePut";

    @Autowired
    private HxStoragePutService hxStoragePutService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;
    /**
     * 导出所有
     *
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List <HxStoragePutResult> listAll(HxStoragePutParam hxStoragePutParam, String condition,String startTime,String endTime) {
        if (hxStoragePutParam != null && hxStoragePutParam.getGoodsName() != null && hxStoragePutParam.getGoodsName().length > 0) {
            for (int i = 0; i < hxStoragePutParam.getGoodsName().length; i++) {
                if (hxStoragePutParam.getGoodsName()[i] != null) { // 进一步检查数组元素是否为 null
                    hxStoragePutParam.getGoodsName()[i] = hxStoragePutParam.getGoodsName()[i].replace("& #40;", "(").replace("& #41;", ")");
                }
            }
        }
        User user = userService.getcurrentUser();
        hxStoragePutParam.setDeptId(user.getDeptId());
        hxStoragePutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
            hxStoragePutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        return this.hxStoragePutService.findlistAllBySpec(hxStoragePutParam,condition,user.getOperateId());
    }
    @ResponseBody
    @RequestMapping("/listAll1")
    public List <HxStoragePutResult> listAll1(HxStoragePutParam hxStoragePutParam, String condition,String startTime,String endTime) {
        if (hxStoragePutParam != null && hxStoragePutParam.getGoodsName() != null && hxStoragePutParam.getGoodsName().length > 0) {
            for (int i = 0; i < hxStoragePutParam.getGoodsName().length; i++) {
                if (hxStoragePutParam.getGoodsName()[i] != null) { // 进一步检查数组元素是否为 null
                    hxStoragePutParam.getGoodsName()[i] = hxStoragePutParam.getGoodsName()[i].replace("& #40;", "(").replace("& #41;", ")");
                }
            }
        }
        User user = userService.getcurrentUser();
        hxStoragePutParam.setDeptId(user.getDeptId());
        hxStoragePutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
            hxStoragePutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        return this.hxStoragePutService.listAll1(hxStoragePutParam,condition,user.getOperateId());
    }
    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxStoragePut.html";
    }

    /**
     * 跳转到主页面
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("toStorageReturn")
    public String toStorageReturn(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择客户
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/storageReturn.html";
    }

    @Resource
    private HxStoragePutDetailedService hxStoragePutDetailedService;

    @Resource
    private BasicPutgoodsService basicPutgoodsService;
    @Resource
    private HxOrderPutService hxOrderPutService;

    @Resource
    private HxOrderPutDetailedService hxOrderPutDetailedService;

    @Resource
    private HxBasicGoodsService hxBasicGoodsService;

    @Resource
    private HxStorageStockService hxStorageStockService;

    @Resource
    private BasicPositionService basicPositionService;


    @Resource
    private HxBasicPositionGoodsService hxBasicPositionGoodsService;

    @Resource
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Resource
    private HxStorageOffShelfService hxStorageOffShelfService;

    @Resource
    private HxStorageOutDetailedService hxStorageOutDetailedService;
    /**
     * 选择库位
     * @return
     */
    @RequestMapping("tochoiceStorageStock")
    public String tochoiceStorageStock() {
        return PREFIX + "/choiceStorageStock.html";
    }


    /**
     * 选择库位列表
     * @param hxStorageStockParam
     * @param condition
     * @return
     */
    @ResponseBody
    @RequestMapping("/choicelist")
    public LayuiPageInfo choicelist(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        return this.hxStorageStockService.findchoicePageBySpec2(hxStorageStockParam,condition);
    }
    /**
     * 审核回传
     * @author lww
     * @Date 2024-7-13
     */
    @RequestMapping("/btnSubmitExamine")
    @ResponseBody
    @Permission
    @Transactional(rollbackFor = Exception.class,timeout=80000)
    public ResponseData btnSubmitExamine(Integer[] ids) {
        if(ids.length >0 && ids != null){
            for (Integer id : ids) {
                HxStoragePut hxStoragePut = this.hxStoragePutService.getById(id);

                HxStoragePutParam hxStoragePutParam = new HxStoragePutParam();
                hxStoragePutParam.setStorageNumber(hxStoragePut.getStorageNumber());
                HxStoragePutResult hxStoragePutResult = hxStoragePutService.findBySpec(hxStoragePutParam);//入库单

               if (hxStoragePutResult.getStorageState().equals("已完成")) {
                   return ResponseData.error("该入库单已完成，请不要重复操作！");
               }
                HxOrderPutParam hxOrderPutParam = new HxOrderPutParam();
                hxOrderPutParam.setOrderPutNumber(hxStoragePut.getStorageNumber());
                HxOrderPutResult hxOrderPutResult = hxOrderPutService.findBySpec(hxOrderPutParam);//入库订单


                // 在入库完成之后，将入库单信息通过调用新增入库单接口，将入库单来回传给新零帮
                BasicWarehouse w = basicWarehouseService.getById(hxStoragePutResult.getGetWarehouseId());
                BasicCustomer r = basicCustomerService.getById(hxStoragePut.getCustomerId());
                if(ToolUtil.isNotEmpty(r.getGsnumber())&&ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
                   if(ToolUtil.isNotEmpty(r.getModeTms())&&r.getModeTms().equals("3")) {
                        if(ToolUtil.isNotEmpty(r.getXlbStorehouseId())) {
                            BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
                                    .eq(BasicPutgoods::getId, hxOrderPutResult.getSetUnitId())
                                    .last("LIMIT 1")
                                    .one();

                            //在入库完成之后，将入库单信息通过调用新增入库单接口，将入库单来回传给新零帮
                            //String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.inorder.save";
                            String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.inorder.save";
                            List <HxStoragePutDetailed> lists = hxStoragePutDetailedService.lambdaQuery()
                                    .eq(HxStoragePutDetailed::getStorageNumber, hxStoragePutResult.getStorageNumber())
                                    .orderByAsc(HxStoragePutDetailed::getGoodsId)
                                    .orderByDesc(HxStoragePutDetailed::getRealNum)
                                    .list();

//                            List <HxStoragePutDetailedResult> storagePutDetailsList = hxStoragePutDetailedService.findStoragePutDetailsList(hxStoragePutDetailedParam);
                            JSONArray ordersArray = new JSONArray();
                            Long zpgoodsid = null;
                            Map <Long, BigDecimal> remainingZpnumMap = new HashMap <>(); // 记录剩余的赠品数量
                            for (HxStoragePutDetailed hxStoragePutDetailed:lists){
                                if(!hxStoragePutDetailed.getPutState().equals("已上架")) {
                                    continue;
                                }
                                if(zpgoodsid == null){
                                    zpgoodsid = hxStoragePutDetailed.getGoodsId();
                                } else {
                                    if(!zpgoodsid.equals(hxStoragePutDetailed.getGoodsId())){
                                        zpgoodsid = hxStoragePutDetailed.getGoodsId();
                                    }
                                }
                                JSONObject orderObject = new JSONObject();

                                HxBasicGoods goods = hxBasicGoodsService.lambdaQuery()
                                        .eq(HxBasicGoods::getId, hxStoragePutDetailed.getGoodsId())
                                        .last("LIMIT 1").one();

                                HxOrderPutDetailed order = hxOrderPutDetailedService.lambdaQuery()
                                        .eq(HxOrderPutDetailed::getOrderPutNumber, hxOrderPutResult.getOrderPutNumber())
                                        .eq(HxOrderPutDetailed::getGoodsId, hxStoragePutDetailed.getGoodsId())
                                        .last("LIMIT 1")
                                        .one();

                                if (goods != null && order != null && ToolUtil.isNotEmpty(order.getZpNum())) {
                                    // 获取该商品的赠品数量信息
                                    BigDecimal zpnum = new BigDecimal(order.getZpNum());
                                    BigDecimal realQuantity = new BigDecimal(hxStoragePutDetailed.getRealNum());
                                    if (!remainingZpnumMap.containsKey(hxStoragePutDetailed.getGoodsId())) {
                                        remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), zpnum);
                                    }
                                    BigDecimal remainingZpnum = remainingZpnumMap.getOrDefault(hxStoragePutDetailed.getGoodsId(), BigDecimal.ZERO);

                                    if (remainingZpnum.compareTo(BigDecimal.ZERO) != 0 ) {
                                        // 在数量大于赠品数量的明细中添加赠品数量
                                        BigDecimal zpRate = new BigDecimal(order.getZpRate());
                                        BigDecimal zpnum_real = remainingZpnum.multiply(zpRate).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                        BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
                                        BigDecimal result = realnum.subtract(remainingZpnum);

                                        BigDecimal jibenrate = new BigDecimal(order.getRate());
                                        if (realQuantity.compareTo(remainingZpnum)>=0){
                                            orderObject.put("present_quantity", remainingZpnum); // 赠品数量 必填
                                            orderObject.put("basic_present_quantity", zpnum_real); // 赠品基本数量 必填
                                            orderObject.put("quantity", result);//数量 必填
                                            orderObject.put("basic_quantity",result.multiply(jibenrate) );//基本数量 必填
                                            remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), BigDecimal.ZERO); // 重置剩余赠品数量
                                        }else if (realQuantity.compareTo(remainingZpnum)<0){
                                            orderObject.put("present_quantity", realQuantity); // 赠品数量 必填
                                            BigDecimal  basic_present_quantity = realQuantity.multiply(zpRate).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                            orderObject.put("basic_present_quantity", basic_present_quantity); // 赠品基本数量 必填
                                            orderObject.put("quantity", BigDecimal.ZERO);//数量 必填
                                            orderObject.put("basic_quantity",BigDecimal.ZERO);//基本数量 必填
                                            remainingZpnumMap.put(hxStoragePutDetailed.getGoodsId(), remainingZpnum.subtract(realQuantity)); // 更新剩余赠品数量
                                        }

                                    } else {
                                        BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
                                        BigDecimal jibenrate = new BigDecimal(order.getRate());

                                        orderObject.put("present_quantity", BigDecimal.ZERO); // 其他托的赠品数量为0
                                        orderObject.put("basic_present_quantity", BigDecimal.ZERO); // 其他托的赠品基本数量为0
                                        orderObject.put("quantity", realnum);//数量 必填
                                        orderObject.put("basic_quantity",realnum.multiply(jibenrate) );//基本数量 必填

                                    }
                                } else {
                                    BigDecimal realnum = new BigDecimal(hxStoragePutDetailed.getRealNum());
                                    BigDecimal jibenrate = new BigDecimal(order.getRate());

                                    orderObject.put("present_quantity", BigDecimal.ZERO); // 没有赠品数量的情况下赠品数量为0
                                    orderObject.put("basic_present_quantity", BigDecimal.ZERO); // 没有赠品数量的情况下赠品基本数量为0
                                    orderObject.put("quantity", realnum);//数量 必填
                                    orderObject.put("basic_quantity",realnum.multiply(jibenrate) );//基本数量 必填

                                }
                                // 创建订单对象

                                orderObject.put("basic_unit",order.getUnit());//基本单位 必填
                                LocalDate productionDate = LocalDate.parse(hxStoragePutDetailed.getDetailedDate());
                                // 保质期（以月份表示）
                                String shelfLifeMonths =goods.getGoodsWarranty();
                                LocalDateTime outputDateTime = productionDate.atStartOfDay();

                                // 计算到期日期
                                LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));
                                // 格式化输出到期日期
                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                LocalDateTime expiryDateTime = expiryDate.atStartOfDay();

                                String formattedExpiryDate = expiryDateTime.format(formatter);// 格式化输出到期日期
                                String deliveryDate = outputDateTime.format(formatter);// 格式化输出生产日期
                                orderObject.put("expire_date", formattedExpiryDate);//	到期日期
                                orderObject.put("item_code", hxStoragePutDetailed.getGoodsNumber());//商品条码
                                orderObject.put("item_bar_code", goods.getGoodsPcode69());
                                orderObject.put("item_id",goods.getGoodsXlbId());//商品id 必填
                                orderObject.put("item_name",hxStoragePutDetailed.getGoodsName() );//商品名称 必填
                                orderObject.put("item_spec",hxStoragePutDetailed.getGoodsSpecs() );//规格
                                orderObject.put("memo","" );//备注
                                orderObject.put("present_ratio",order.getZpRate());//	赠品换算率 必填
                                orderObject.put("present_unit",order.getZpUnit());//	赠品单位 必填
                                orderObject.put("producing_date",deliveryDate);//生产日期
                                orderObject.put("ratio", hxStoragePutDetailed.getRate());//换算率 必填
                                orderObject.put("storage_id",hxStoragePutDetailed.getXlbPositionId());//	库位id
                                orderObject.put("storage_name",hxStoragePutDetailed.getPositionNumber());//库位名称
                                orderObject.put("unit", hxStoragePutDetailed.getUnit());//单位 必填
                                ordersArray.put(orderObject);
                            }


                            JSONObject json = new JSONObject();
                            json.put("adjust_reason_name", "");//调整原因
                            json.put("client_id",basicPutgoods.getXlbClientId());// 发货客户id
                            json.put("client_name", basicPutgoods.getPutgoodsName());//发货客户名称
                            json.put("details", ordersArray);//明细
                            json.put("memo","" );//备注
                            json.put("order_fid",hxOrderPutResult.getOrderPutNumber());
                            json.put("wms_fid", hxOrderPutResult.getOrderPutNumber());
                            if (hxOrderPutResult.getOrderType().equals("门店调入")){
                                json.put("order_type","STORE_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            if (hxOrderPutResult.getOrderType().equals("采购收货")){
                                json.put("order_type","RECEIVE" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            if (hxOrderPutResult.getOrderType().equals("批发退货")){
                                json.put("order_type","WHOLESALE_RETURN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            if (hxOrderPutResult.getOrderType().equals("调整入库")){
                                json.put("order_type","ADJUST_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            if (hxOrderPutResult.getOrderType().equals("甩货入库")){
                                json.put("order_type","DUMP_IN" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            if (hxOrderPutResult.getOrderType().equals("仓间调拨")){
                                json.put("order_type","TRANSFER" );//入库单据类型：STORE_IN(门店调入),RECEIVE(采购收货),WHOLESALE_RETURN(批发退货),ADJUST_IN(调整入库),DUMP_IN(甩货入库),可用值:ADJUST_IN,DUMP_IN,RECEIVE,STORE_IN,WHOLESALE_RETURN
                            }
                            json.put("store_id",r.getStoreIdXlb());
                            json.put("storehouse_id", w.getWarehouseXlbId());
//                            System.out.println(json.toString());

                            BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
                            oauth2tokenParam.setDeliverId(r.getDeliverId());
                            oauth2tokenParam.setGsnumber(r.getGsnumber());
                            BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

                            if(ordersArray.length() > 0) {
                            	String response = HttpRequest.post(url)
            							.timeout(60000)
                            			.header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                            			.body(json.toString()).execute().body();
                            	//System.out.println("================json："+json+"========================");
                            	//System.out.println("================post："+response+"========================");
                            	JSONObject jsonObject = new JSONObject(response);
//                                System.out.println(jsonObject.toString());
                            	if (jsonObject.get("code").toString().equals("0")) {

                            		hxOrderPutService.lambdaUpdate()
                            		.set(HxOrderPut::getReturnStatus,"已完成")
                            		.eq(HxOrderPut::getOrderPutNumber,hxOrderPutResult.getOrderPutNumber())
                            		.update();

                            		hxOrderPutParam.setId(hxOrderPutResult.getId());
                            		hxOrderPutParam.setOrderState("已完成");
                            		hxOrderPutParam.setCompleteTime(new Date());
                            		hxOrderPutService.update(hxOrderPutParam);


                            		hxStoragePutParam.setId(hxStoragePutResult.getId());
                            		hxStoragePutParam.setStorageState("已完成");
                            		hxStoragePutParam.setCompleteTime(new Date());
                            		hxStoragePutService.update(hxStoragePutParam);

                            		for (HxStoragePutDetailed hxStoragePutDetailed:lists){
                            			if(hxStoragePutDetailed.getPutState().equals("已上架")) {
                            				hxStorageStockService.lambdaUpdate()
                            				.eq(HxStorageStock::getId, hxStoragePutDetailed.getStockId())
                            				.set(HxStorageStock::getStockState, "正常")
                            				.update();
                            			}
                            		}

                            		//System.out.println(jsonObject.toString());
                            		Object data = jsonObject.get("data");
                            		return ResponseData.success("回传成功");
                            	} else {
                            		//System.out.println(jsonObject.toString());
                            		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
                            		return ResponseData.error("回传失败");
                            	}
                            }
                        }
                    }
                }


            }
        }


        return ResponseData.success();
    }

    /**
     * 审核回传
     * @author lww
     * @Date 2024-7-13
     */
    @RequestMapping("/btnsdwc")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class,timeout=80000)
    public ResponseData btnsdwc(Integer[] ids) {
        if(ToolUtil.isEmpty(ids)){
            return ResponseData.error("请选择记录后重试");
        }

        this.hxStoragePutService.lambdaUpdate()
                .in(HxStoragePut::getId,ids)
                .set(HxStoragePut::getStorageState,"已完成")
                .update();
        return ResponseData.success();
    }
        /**
         * 新增页面
         *
         * @author zhucx
         * @Date 2023-08-14
         */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/hxStoragePut_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/hxStoragePut_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxStoragePutParam hxStoragePutParam) {
        this.hxStoragePutService.add(hxStoragePutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxStoragePutParam hxStoragePutParam) {
        this.hxStoragePutService.update(hxStoragePutParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxStoragePutParam hxStoragePutParam) {
        this.hxStoragePutService.delete(hxStoragePutParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxStoragePutParam hxStoragePutParam) {
        HxStoragePut detail = this.hxStoragePutService.getById(hxStoragePutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxStoragePutParam hxStoragePutParam,String condition ,String startTime,String endTime) {
        if (hxStoragePutParam != null && hxStoragePutParam.getGoodsName() != null && hxStoragePutParam.getGoodsName().length > 0) {
            for (int i = 0; i < hxStoragePutParam.getGoodsName().length; i++) {
                if (hxStoragePutParam.getGoodsName()[i] != null) { // 进一步检查数组元素是否为 null
                    hxStoragePutParam.getGoodsName()[i] = hxStoragePutParam.getGoodsName()[i].replace("& #40;", "(").replace("& #41;", ")");
                }
            }
        }
        User user = userService.getcurrentUser();
    	hxStoragePutParam.setDeptId(user.getDeptId());
    	if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
    		hxStoragePutParam.setTimeType("cj");
    	}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
        return this.hxStoragePutService.findPageBySpec(hxStoragePutParam,condition,user.getOperateId());
    }
    @ResponseBody
    @RequestMapping("/count")
    public ResponseData count(HxStoragePutParam hxStoragePutParam,String condition ,String startTime,String endTime) {
        if (hxStoragePutParam != null && hxStoragePutParam.getGoodsName() != null && hxStoragePutParam.getGoodsName().length > 0) {
            for (int i = 0; i < hxStoragePutParam.getGoodsName().length; i++) {
                if (hxStoragePutParam.getGoodsName()[i] != null) { // 进一步检查数组元素是否为 null
                    hxStoragePutParam.getGoodsName()[i] = hxStoragePutParam.getGoodsName()[i].replace("& #40;", "(").replace("& #41;", ")");
                }
            }
        }
        User user = userService.getcurrentUser();
        hxStoragePutParam.setDeptId(user.getDeptId());
        hxStoragePutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
            hxStoragePutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        return ResponseData.success(this.hxStoragePutService.count(hxStoragePutParam,condition,user.getOperateId()));

    }
    @ResponseBody
    @RequestMapping("/count1")
    public ResponseData count1(HxStoragePutParam hxStoragePutParam,String condition ,String startTime,String endTime) {
        User user = userService.getcurrentUser();
        hxStoragePutParam.setDeptId(user.getDeptId());
        hxStoragePutParam.setDeliverId(user.getDeliverId());
        if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
            hxStoragePutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        return ResponseData.success(this.hxStoragePutService.count1(hxStoragePutParam,condition,user.getOperateId()));

    }
    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-14
     */
    @ResponseBody
    @RequestMapping("/returnlist")
    public LayuiPageInfo returnlist(HxStoragePutParam hxStoragePutParam,String condition ,String startTime,String endTime) {
        if (hxStoragePutParam != null && hxStoragePutParam.getGoodsName() != null && hxStoragePutParam.getGoodsName().length > 0) {
            for (int i = 0; i < hxStoragePutParam.getGoodsName().length; i++) {
                if (hxStoragePutParam.getGoodsName()[i] != null) { // 进一步检查数组元素是否为 null
                    hxStoragePutParam.getGoodsName()[i] = hxStoragePutParam.getGoodsName()[i].replace("& #40;", "(").replace("& #41;", ")");
                }
            }
        }
        User user = userService.getcurrentUser();
    	hxStoragePutParam.setDeptId(user.getDeptId());
    	if(ToolUtil.isEmpty(hxStoragePutParam.getTimeType())) {
    		hxStoragePutParam.setTimeType("cj");
    	}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			hxStoragePutParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
        return this.hxStoragePutService.findreturnPageBySpec(hxStoragePutParam,condition,user.getOperateId());
    }



    /**
     * 入库质检信息统计
     *
     * @author lww
     * @Date 2023-11-15
     */
    @ResponseBody
    @RequestMapping("/getQualityUser")
    public LayuiPageInfo getqualityuser(HxStoragePutParam hxStoragePutParam , String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxStoragePutParam.setDeptId(user.getDeptId());
        hxStoragePutParam.setOperateId(user.getOperateId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutParam.setTimeInterval("'"+ DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }

        String[] StorageState={"待上架","已上架"};
        hxStoragePutParam.setStorageState1(StorageState);
        return this.hxStoragePutService.getqualityuser(hxStoragePutParam,condition);
    }

    /**
     * 上架人员信息统计
     *
     * @author lww
     * @Date 2023-11-15
     */
    @ResponseBody
    @RequestMapping("/shangjiauser")
    public LayuiPageInfo shangjiauser(HxStoragePutDetailedParam hxStoragePutDetailedParam , String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxStoragePutDetailedParam.setDeptId(user.getDeptId());
        hxStoragePutDetailedParam.setOperateId(user.getOperateId());
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxStoragePutDetailedParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            hxStoragePutDetailedParam.setTimeInterval("'"+ DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        hxStoragePutDetailedParam.setPutState("已上架");
        return this.hxStoragePutService.shangjiauser(hxStoragePutDetailedParam,condition);
    }

}


